const mysql = require('mysql2/promise');

// 数据库连接配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'jiangwei0594', 
  database: 'zdzdxcx_db'
};

// 创建连接池
const pool = mysql.createPool(dbConfig);

// 测试数据库连接
async function testConnection() {
  try {
    const connection = await pool.getConnection();
    console.log('数据库连接成功');
    connection.release();
    return true;
  } catch (error) {
    console.error('数据库连接失败:', error);
    return false;
  }
}

// 创建连接池函数
async function createPool() {
  try {
    const connection = await pool.getConnection();
    console.log('数据库连接池创建成功');
    connection.release();
    return pool;
  } catch (error) {
    console.error('数据库连接池创建失败:', error);
    throw error;
  }
}

// 在数据库连接成功后添加以下代码
pool.query('SHOW TABLES').then(([rows]) => {
  console.log('数据库表列表:', rows.map(row => Object.values(row)[0]));
  
  // 检查departments表结构
  return pool.query('DESCRIBE departments');
}).then(([rows]) => {
  console.log('departments表结构:', rows);
}).catch(err => {
  console.error('查询表结构失败:', err);
});

module.exports = {
  pool,
  testConnection,
  createPool
};